import java.util.*;

public class Practice2 {
    //https://leetcode.cn/problems/sort-an-array/description/
    //排序数组, 使用随机快速排序, 也可以使用归并
    public int[] sortArray(int[] nums) {
        qsort(nums,0,nums.length - 1);
        return nums;
    }

    private void qsort(int[] nums, int left, int right) {
        if(left >= right){
            return;
        }
        //分成三块[0,l] [l + 1,r - 1] [r, right]
        //分别代表小于key    等于key      大于key
        int l = left - 1;
        int r = right + 1;
        int key = nums[new Random().nextInt(right - left + 1) + left];
        //i要从left开始, 不能从0
        int i = left;
        //i小于r即可, 不需要小于right, 因为[r, right]代表大于key的
        while(i < r){
            if(nums[i] < key){
                swap(nums,++l,i++);
            }else if(nums[i] == key){
                i++;
            }else{
                swap(nums,--r,i);
            }
        }
        //左排排
        qsort(nums,left,l);
        //右排排
        qsort(nums,r,right);
    }

    private void swap(int[] nums, int a, int b) {
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }

    public static void main(String[] args) {

    }
}
